"""Service资源提取器模块"""

from typing import Dict, Any, Optional
import logging
from src.extractors.base import Extractor

class ServiceExtractor(Extractor):
    """
    Service资源提取器
    负责从Service资源定义中提取关键信息
    """
    
    def __init__(self, logger: Optional[logging.Logger] = None):
        """初始化Service提取器"""
        super().__init__(logger)
        self.resource_type = "Service"
    
    def extract(self, content: str, file_path: str = "") -> Dict[str, Any]:
        """
        从Service YAML/JSON内容中提取信息
        
        Args:
            content: YAML/JSON格式的资源内容
            file_path: 资源文件路径，可选，用于日志记录
            
        Returns:
            提取的Service资源信息字典
        """
        # 解析YAML/JSON内容
        resource = self.parse_content(content, file_path)
        if not resource:
            return {}
            
        # 检查是否为Service资源
        if resource.get("kind") != "Service":
            self.logger.warning(f"资源不是Service: {file_path}")
            return {}
            
        # 提取基本信息
        result = self._extract_basic_info(resource)
        
        # 提取Service特有信息
        self._extract_service_info(resource, result)
        
        return result
    
    def _extract_basic_info(self, resource: Dict[str, Any]) -> Dict[str, Any]:
        """
        提取基本元数据信息
        
        Args:
            resource: 解析后的资源字典
            
        Returns:
            包含基本信息的字典
        """
        metadata = resource.get("metadata", {})
        
        result = {
            "kind": "Service",
            "name": metadata.get("name", ""),
            "namespace": metadata.get("namespace", "default"),
            "creation_timestamp": metadata.get("creationTimestamp", "")
        }
        
        # 提取标签和注解
        if "labels" in metadata:
            result["labels"] = metadata.get("labels", {})
            
        if "annotations" in metadata:
            result["annotations"] = metadata.get("annotations", {})
            
        return result
    
    # 为了向后兼容，添加别名
    def extract_base_info(self, resource: Dict[str, Any]) -> Dict[str, Any]:
        """提取基本信息的兼容方法，调用_extract_basic_info"""
        return self._extract_basic_info(resource)
    
    def _extract_service_info(self, resource: Dict[str, Any], result: Dict[str, Any]) -> None:
        """
        提取Service特有信息
        
        Args:
            resource: 解析后的资源字典
            result: 要填充的结果字典
        """
        spec = resource.get("spec", {})
        
        # 服务类型
        if "type" in spec:
            result["service_type"] = spec["type"]
        
        # 集群IP
        if "clusterIP" in spec:
            result["cluster_ip"] = spec["clusterIP"]
            
        # 端口信息
        if "ports" in spec:
            ports = []
            for port in spec["ports"]:
                port_info = {}
                if "name" in port:
                    port_info["name"] = port["name"]
                if "port" in port:
                    port_info["port"] = port["port"]
                if "targetPort" in port:
                    port_info["target_port"] = port["targetPort"]
                if "nodePort" in port:
                    port_info["node_port"] = port["nodePort"]
                if "protocol" in port:
                    port_info["protocol"] = port["protocol"]
                ports.append(port_info)
            result["ports"] = ports
        
        # 选择器
        if "selector" in spec:
            result["selector"] = spec["selector"]
            
        # 外部IP
        if "externalIPs" in spec:
            result["external_ips"] = spec["externalIPs"]
            
        # 会话亲和性
        if "sessionAffinity" in spec:
            result["session_affinity"] = spec["sessionAffinity"]